package charlie.shop.web;

import com.charlie.sessions.CartLocal;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * Web application lifecycle listener.
 *
 * @author Vitaliy Mostipaka <imprtat@gmail.com>
 */
@WebListener()
public class SessionListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        CartLocal cart = null;
        session.setAttribute("user", null);
        try {
            InitialContext context = new InitialContext();
            cart = (CartLocal) context.lookup("java:global/CharlieShop/CharlieShop-ejb/Cart");
        } catch (NamingException ex) {
            Logger.getLogger(SessionListener.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
        }
        session.setAttribute("cart", cart);
    }
    /**
     * Release resources after session closed
     * @param se 
     */
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        session.setAttribute("user", null);
        session.setAttribute("cart", null);
    }
}
